package cn.edu.sjtu.software.sjtucontacts.service.security;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


//AES Encryption Algorithm
public class AESEncryptionAlgorithm implements IEncryption {
	private static final String keyString = "helloworldtoscon";
	private static final String ivString = "0102030405060708";

	@Override
	public OutputStream encrypt(String path) throws Exception{
		// TODO Auto-generated method stub
		byte[] raw = keyString.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(ivString.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        FileOutputStream fos = new FileOutputStream(path);
        CipherOutputStream cos = new CipherOutputStream(fos, cipher);
		return cos;
	}

	@Override
	public InputStream decrypt(String path) throws Exception{
		// TODO Auto-generated method stub
		byte[] raw = keyString.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(ivString.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        FileInputStream fis = new FileInputStream(path);
        CipherInputStream cis = new CipherInputStream(fis, cipher);
		return cis;
	}
}
